/*
 * @name ajaxLib.js
 * @author : Amissah Gideon<kuulmek@yahoo.com>
 * @version 1.0
*/

Number.prototype.formatMoney = function(c, d, t){
var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};


var jLib = {
       /* Function init
        * This function is the entry point of the Object.
        * @param void
        * @return void
        * @access public
        * */
       init:function(){
            $("#loader_bar").hide(); 
			/*Show a loading message whenever an Ajax request starts (and none is already active).*/
			$("#loader_bar").ajaxStart(function(){
				$(this).show();
			});

			$("#loader_bar").ajaxStop(function(){
			  $(this).hide();
			});
            
            $('#feedback_bar').click(function(){ 
                $('#feedback_bar').fadeTo("fast",0);
            });
       },
	   
       afterClosePopUpForm:function(form, callback){
         $(document).bind('cbox_closed', function(){
           document.getElementById(form).reset();
           $.validationEngine.closePrompt('.formError',true);
           if(typeof callback === 'function'){
                callback();
           }
        });
       }, 
        
       showModal: function(){
            $('#modal_blanket').show();
       },
        
       hideModal: function(){
            $('#modal_blanket').hide();
       },
        
       highlightRow: function(grid){
           $('.trSelected', grid).each(function() {
                $(this).removeClass('trSelected');
                var chk = $(this).find(':checkbox').attr('checked');
                if(typeof chk != "undefined"){
                    $(this).find(':checkbox').attr('checked','');
                    //console.log(' Ob :'+chk)
                }
                var has_class = false;
                if($(this).hasClass('erow')){
                   $(this).removeClass('erow');
                   has_class = true;
                }
                $(this).animate({backgroundColor:"#bbe4ff"},"slow","linear")
        		.animate({backgroundColor:"#bbe4ff"},4000)
        		.animate({backgroundColor:"#ffffff"},"slow","linear",function() {
                    // Animation complete.
                    if(has_class){
                       $(this).addClass('erow');
                    }
                });
            });
			return;
        },
        
        updateGridData:function(grid, data){
            $('.trSelected', grid).each(function() {
                var tr = $(this);
                $(tr).find('td').each(function(){
                    var val = data[$(this).attr('field')];
                    if(typeof val != 'undefined'){
                        $(this).find('div').html(val);
                    }
                })
            });
        },
        
        removeGridRows:function(grid){
            $('.trSelected', grid).each(function() {
                //$(this).removeClass('trSelected');
                $(this).animate({backgroundColor:"#bbe4ff"},1200,"linear")
        		.animate({opacity:0},1200,"linear",function() {
                    $(this).remove();
                });
            });
        },
                
        countSelectedRows:function(grid){
			var selected_values = 0;
            $('.trSelected', grid).each(function() {
                selected_values = selected_values + 1;
            });
			return selected_values;
		},
        
        rowSelectedCheck:function(grid,limit){
            var count = jLib.countSelectedRows(grid);
            if(limit){
                if(count < limit){
    			  jAlert("At least "+limit+" Record(s) needs to be selected prior to this action",'Alert');
    			  return false;
    			 }
                 else if(count > limit){
    			     jAlert("Only "+limit+" Record(s) at a time",'Alert');
    			  return false;
    			}
            }
            else{
                if(count == 0){
    			  jAlert("At least 1 Record needs to be selected prior to this action",'Alert');
    			  return false;
    			 }
            }
           
            return true
		},
        
		getSelectedRowIds:function(grid){
			var selected_values = new Array();
            $('.trSelected', grid).each(function() {
                var id = $(this).attr('id');
                id = id.substring(id.lastIndexOf('row')+3);
                selected_values.push(id);
            });
			return selected_values;
		},

		getSelectedRows:function (grid){
			var selected_rows = new Array();
            $('.trSelected', grid).each(function() {
                selected_values.push($(this));
            });
			return selected_rows;
		},
		
		setFeedback:function (text, type, keep_displayed){
            var classname = 'color-block color-block-2';
            if(type == 'error_message'){
			  classname = 'color-block color-block-1'
			}
            else if(type == 'warning_message'){
                classname = 'color-block color-block-3'
            }
            if(text!='')
			{
				$('#feedback_bar > div').removeClass();
				$('#feedback_bar > div').addClass(classname);
				$('#feedback_bar > div > .inside > span').text(text);
				$('#feedback_bar').css('opacity','1');
                $('#feedback_bar').css('z-index','2104');
    
				if(!keep_displayed){
					$('#feedback_bar').fadeTo(5000, 1);
					$('#feedback_bar').fadeTo("fast",0);
                    $('#feedback_bar').css('z-index','500');
				}
			}
			else{
				$('#feedback_bar').css('opacity','0');
                $('#feedback_bar').css('z-index','500');
			}
		},
        
        builPopUpPrompt:function (domObj,text, type, keep_displayed){
           $.validationEngine.buildPrompt(domObj,text,type);
           if(!keep_displayed){
				setTimeout(function(){
                     $.validationEngine.closePrompt('.formError',true)
               },5000);
		   }
           
		},
        
        
        menuAccordion:function (id){
			$('#'+id+' ul > li ul')
                .click(function(e){
                  e.stopPropagation();
                    $(this).parent().addClass("active");                  
                })
                .filter(':not(:first)')
                .hide();
                
              $('#'+id+' ul > li').click(function(){
                var type = this;
                var selfClick = $(this).find('ul:first').is(':visible');
                if(!selfClick) {
                  $(this)
                    .parent()
                    .find('> li ul:visible')
                    .slideToggle();
                }
                
                $(this)
                  .find('ul:first')
                  .stop(true, true)
                  .slideToggle();
                  
                $(this).addClass("active");
                $('#'+id+' ul > li').each(function() {
                    if( this != type ) {
                       $(this).removeClass("active");
                    }
                });                  
                  
              });
		},
        
        
         /*Universal Delete for all jQuery DataTable*/
	   do_delete:function (url,grid, callback){
			var row_ids = jLib.getSelectedRowIds(grid);
			//var selected_rows = jLib.getSelectedRows(table_id);
             jConfirm('Are you sure you want to continue ?', 'Confirm', function(confirmation) {
                    if(confirmation){
                        $.post(url, {'ids[]': row_ids},function(response){
                              //delete was successful, remove checkbox rows
                              if(response.code == 0){
                                    jLib.removeGridRows(grid);
                                    jLib.setFeedback(response.mesg,'success_message',false);
                                    
                                    if(typeof callback == 'function'){
                                        callback();
                                    }
                              }
                              else if(response.code == 1){
                                    jLib.setFeedback(response.mesg,'error_message',false);
                              }
                        },"json");
                    }
             });
		},
        
        //////////////////////Order General Functions
        array_diff: function(a1, a2){
              var a=[], diff=[];
              for(var i=0;i<a1.length;i++)
                a[a1[i]]=true;
              for(var i=0;i<a2.length;i++)
                if(a[a2[i]]) delete a[a2[i]];
                else a[a2[i]]=true;
              for(var k in a)
                diff.push(k);
              return diff;
        }
        
        
};

/* when the page is loaded */
$(document).ready(function() {
	//Hiding the loader bar
       jLib.init();
});

